<?php

namespace App\Http\Controllers\Back;

use App\Common\Constant;
use App\Http\Controllers\Controller;
use App\Http\Requests\OperatorsRequest;
use App\Model\Operators;
use App\Model\Partner;
use App\Model\SmsMsg;
use App\Model\UserBill;
use App\User;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OperatorsController extends Controller
{

    public function index(Request $request, Partner $partner, Operators $operators)
    {

        $where = [];
        //当前用户不是管理员,当前所属城市代理商
        if ($request->user()->type == 1) {
            $p = $partner->where(['user_id' => $request->user()->id])->first();
            if (empty($p)){
                return $this->renderJson();
            }
            //管理员看见全部，合伙人看见合伙人下属
            $where['place_partner_id'] = $p->id;
        }

        $o = $operators->getPaginate($request, $where);

        return $this->renderJson($o);
    }

    /**
     * @param $id
     * @param Request $request
     * @param Partner $partner
     * @param Operators $operators
     * @return \Illuminate\Http\Response
     * @throws AuthorizationException
     */
    public function show($id, Request $request, Partner $partner, Operators $operators)
    {
        $p = $partner->where(['user_id' => $request->user()->id])->first();
        $operator = $operators->findOrFail($id);
//        if ($p->id != $operator->place_partner_id && $request->user()->type != 0){
//            throw new AuthorizationException();
//        }
        return $this->renderJson($operator);
    }

    public function store(OperatorsRequest $request, Partner $partner, Operators $operators, User $user)
    {
        if ($user->where('phone','=',$request->input('phone'))->first()){
            return $this->fail('该手机号已经被注册过了');
        }
        (new SmsMsg())->validate(\request('phone'), \request('sms_code'));
        //当前用户下是否满了
        $p = $partner->where('user_id', $request->user()->id)->first();
        $count = $operators->where(['place_partner_id'=>$p->id])->count();
        if ($count >= $p->operators_num){
            return $this->fail("您已添加{$p->operators_num}个运营商，不能继续添加！");
        }

        $operators->fill($request->all());
        $operators->place_partner_id = $p->id;


        try {
            DB::beginTransaction();
            $operators->save();

            //上级增加数量
            $p->increment('operator_count');
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->error('添加失败');
        }
        return $this->success();
    }

    public function update(OperatorsRequest $request, $id, Operators $operators)
    {
        $operator = $operators->findOrFail($id);
        $operator->fill($request->all());

        if ($operator->save()) {
            return $this->renderJson();
        }
        return $this->error('修改失败');
    }

    public function destroy($id, Operators $operators)
    {
        $operator = $operators->findOrFail($id);
        try {
            $res = $operator->delete();
            if ($res){
                return $this->success();
            }
        } catch (\Exception $e) {
        }
        return $this->error('删除失败');
    }

    public function stop(Request $request, $id, Operators $operators)
    {
        $this->validate($request, [
            'status' => 'boolean'
        ]);
        $status = $request->input('status');
        $o = $operators->findOrFail($id);
        $o->status = $status;
        $o->user->is_enabled = $status;
        if ($o->save()) {
            return $this->success();
        }
        return $this->error('修改失败');
    }

    public function examines(Operators $operators)
    {
        return $this->renderJson($operators->examines());
    }

    public function examine($id)
    {

        try {
            DB::transaction(function () use ($id) {
                $o = Operators::findOrFail($id);
                $user = new User;
                $user->account = $o->phone;
                $user->phone = $o->phone;
                $user->password = bcrypt('123456');
                $user->type = 2;
                $user->is_enabled = 0;
                $user->save();

                $o->examine = 1;
                $o->user_id = $user->id;
                $o->examined_at = date('Y-m-d H:i:s', time());
                $o->save();

                $p = Partner::find($o->place_partner_id);
                $user->place_partner_id = $p->user_id;
                $user->save();
//                $p_user = User::find($p->user_id);
                //城市合伙人收益
                $amount = $o->agency_fee * Constant::OPERATORS_PARTNER;
//                $p_user->increment('money', $amount);
//                $p_user->increment('availableAmount', $amount);
//                $p_user->increment('agency_fee', $amount);

                //日志
                $bill = new UserBill;
                $bill->user_id = $p->user_id;
                $bill->type = 1;
                $bill->title = '运营商代理分成60%';
                $bill->amount = $amount;
                $bill->save();
            });
            return $this->success();
        } catch (\Throwable $e) {
            return $this->error('设置失败');
        }
    }

    public function manageCenterList()
    {
        $p = DB::table('place_partners')->select('id','title')->get();

        return $this->renderJson($p);
    }
}
